package org.wu.reggie.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wu.reggie.common.R;
import org.wu.reggie.entity.AddressBook;
import org.wu.reggie.service.AddressBookService;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequestMapping("/addressBook")
@RestController
public class AddressBookController {


    @Autowired
    private AddressBookService addressBookService;


    @GetMapping("/list")
    public R<List<AddressBook>> list(HttpSession session){

        Long userId = (Long) session.getAttribute("user");

        List<AddressBook> addressBookList = addressBookService.queryAddressList(userId);


        return R.success(addressBookList);
    }

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook,HttpSession session){

        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBook.setCreateUser(userId);
        addressBook.setUpdateUser(userId);
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookService.save(addressBook);

        return R.success("添加成功!");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefault(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);

        if (addressBook == null){
            return R.error("请设置默认地址");
        }else {
            return R.success(addressBook);
        }



    }





}
